package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.mapper.RoleMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper mapper;

    @Override
    public void deleteByPrimaryKey(Long id) {

        mapper.deleteByPrimaryKey(id);
        mapper.deleteRolePermissionRelations(id);
        mapper.deleteRoleSystemMenuRelations(id);
    }

    @Override
    public void insert(Role entity,Long[] pemissionIds,Long[] systemMenuIds) {
        mapper.insert(entity);
        //1.先保存角色对象,然后进行角色和权限之间的保存关系设置
        for (Long pemissionId : pemissionIds) {
            mapper.saveRolePermissionRelations(entity.getId(),pemissionId);
        }
        //2.保存角色和菜单之间的关系
        for (Long systemMenuId:systemMenuIds ) {

            mapper.saveRoleSystemMenuRelations(entity.getId(),systemMenuId);
        }
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {

        return mapper.selectAll();
    }

    @Override
    public void updateByPrimaryKey(Role entity,Long[] pemissionIds,Long[] systemMenuIds) {

        mapper.updateByPrimaryKey(entity);
        //1.先删除两者之间的旧关系
        mapper.deleteRolePermissionRelations(entity.getId());

        //删除角色和菜单之间的关系
        mapper.deleteRoleSystemMenuRelations(entity.getId());
        //2.保存两者的新关系
        for (Long pemissionId : pemissionIds) {
            mapper.saveRolePermissionRelations(entity.getId(),pemissionId);
        }

        //2.保存角色和菜单之间的关系
        for (Long systemMenuId:systemMenuIds ) {

            mapper.saveRoleSystemMenuRelations(entity.getId(),systemMenuId);
        }
    }

    @Override
    public PageResult query(QueryObject qo) {

        Long totalCount = mapper.queryForCount(qo);
        if (totalCount == 0){
            return new PageResult(qo.getPageSize());
        }
        List<Role> listData = mapper.queryForList(qo);
        return new PageResult(listData,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }


}
